﻿using GomokuCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GomokuAI
{
    public class ComputerPlayer : Player
    {
        public override Position Think(PositionStatus[,] board)
        {
            Position minimaxPos = new Position();
            int minimaxScore = int.MaxValue;

            int center = Game.BoardSize / 2;
            for (int rowOffset = 0; rowOffset < center; rowOffset++)
            {
                for (int colOffset = 0; colOffset < center; colOffset++)
                {
                    for (int rowOffsetSign = -1; rowOffsetSign <= 1; rowOffsetSign += 2)
			        {
			            for (int colOffsetSign = -1; colOffsetSign <= 1; colOffsetSign += 2)
			            {
                            int rowMy = center + rowOffset * rowOffsetSign;
                            int colMy = center + colOffset * colOffsetSign;

			                if (board[rowMy, colMy] != PositionStatus.Empty)
                                continue;

                            board[rowMy, colMy] = PositionStatus.White;

                            bool discard = false;
                            int maxScore = int.MinValue;
                            for (int rowOppo = 0; rowOppo < Game.BoardSize; rowOppo++)
                            {
                                for (int colOppo = 0; colOppo < Game.BoardSize; colOppo++)
                                {
                                    if (board[rowOppo, colOppo] != PositionStatus.Empty)
                                        continue;

                                    board[rowOppo, colOppo] = PositionStatus.Black;

                                    var score = Evaluator.Evaluate(board);

                                    if (score > maxScore)
                                    {
                                        maxScore = score;

                                        if (maxScore > minimaxScore)
                                            discard = true;
                                    }

                                    board[rowOppo, colOppo] = PositionStatus.Empty;

                                    if (discard)
                                        break;
                                }

                                if (discard)
                                    break;
                            }

                            if (maxScore < minimaxScore)
                            {
                                minimaxPos = new Position(rowMy, colMy);
                                minimaxScore = maxScore;
                            }

                            board[rowMy, colMy] = PositionStatus.Empty;
			            }
			        }
                }
            }

            return minimaxPos;
        }
    }
}
